/*
 * @Author: mayijun
 * @Date: 2022-05-14 09:25:52
 * @LastEditors: mayijun
 * @LastEditTime: 2022-07-14 11:17:36
 */
//取数保存任务抽屉
import { defineComponent, onMounted, PropType, reactive, ref, toRaw } from 'vue';
import './index.scss';
import dayjs from 'dayjs';
import _ from 'lodash';
import { ElButton } from 'element-plus';
import API from '@/services';
const TaskSaveDrawer = defineComponent({
  name: 'TaskSaveDrawer',
  props: {
    drawerVisible: {
      type: Boolean as PropType<boolean>,
      default: false
    },
    editData: {
      type: Object,
      default: undefined as any
    },
    saveLoading: {
      type: Boolean as PropType<boolean>,
      default: false
    }
  },
  emits: ['handleClose', 'saveTask'],
  setup: (props, { slots, attrs, emit }) => {

    let ruleFormRef = ref();

    const validateFixdate = (rule: any, value: any, callback: any) => {
      if ((state.ruleForm as any).cycleType === '1' && value === '') {
        callback(new Error('请选择日期'));
      }
      callback();
    };
    const validateFixedTime = (rule: any, value: any, callback: any) => {
      const form = state.ruleForm as any;
      if (
        (form.cycleType === '1' ||
          form.cycleType === '2' ||
          form.cycleType === '3' ||
          form.cycleType === '4') &&
        value === ''
      ) {
        callback(new Error('请选择时间'));
      }
      callback();
    };
    const validateCycleValue = (rule: any, value: any, callback: any) => {
      const form = state.ruleForm as any;
      if ((form.cycleType === '3' || form.cycleType === '4') && value === '') {
        let typeStr = form.cycleType === '3' ? '周' : '月';
        callback(new Error(`请选择${typeStr}`));
      }
      callback();
    };
    let state = reactive({
      loading: false,
      cycleTypes: [] as any[],//周期类型
      weekExecOptions: [] as any[],
      monthExecOptions: [] as any[],
      ruleForm: {
        taskName: '', // 任务名称
        taskDesc: '', // 业务含义
        cycleType: '1', // 任务周期
        expireTime: '', // 过期时间
        fixedDate: '',
        fixedTime: '',
        cycleValue: []
      } as any,
      rules: {
        taskName: [
          {
            required: true,
            message: '请输入任务名称',
            trigger: 'blur'
          }
        ],
        taskDesc: [
          {
            required: true,
            message: '请输入',
            trigger: 'change'
          }
        ],
        cycleType: [
          {
            required: true,
            message: '请选择任务周期',
            trigger: 'change'
          }
        ],
        expireTime: [
          {
            required: true,
            message: '请选择过期时间',
            trigger: 'change'
          }
        ],
        fixedDate: [{ validator: validateFixdate, trigger: 'change' }],
        fixedTime: [{ validator: validateFixedTime, trigger: 'change' }],
        cycleValue: [{ validator: validateCycleValue, trigger: 'change' }]
      }
    });

    const handleClose = () => {
      emit('handleClose');
    }
    const submitForm = (formName: any) => {
      ruleFormRef.value.validate((valid: any) => {
        if (valid) {
          const emitData = _.cloneDeep(toRaw(state.ruleForm));
          emit('saveTask', emitData);
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }
    const resetForm = (formName: any) => {
      ruleFormRef.value.resetFields();
      handleClose();
    }
    const disabledDate = (time: any) => {
      return time.getTime() < dayjs().subtract(1, 'day');
    }
    const handleCycleChange = (val: any) => {
      state.ruleForm.fixedDate = '';
      state.ruleForm.fixedTime = '';
      state.ruleForm.cycleValue = [''] as any;
    }
    //周期类型
    const getCycleTypesOptions = async () => {
      const { code, data } = await API.enumBao.getTaskCycleType();
      if (code === 200 && Array.isArray(data)) {
        state.cycleTypes = data;
      } else {
        console.log('获取cycleTypes失败');
      }
    }
    // 获取周执行枚举
    const getWeekExecOptions = async () => {
      const { code, data } = await API.enumBao.getWeekDay();
      if (code === 200 && Array.isArray(data)) {
        state.weekExecOptions = data;
      } else {
        console.log('获取setWeekExecOptions失败');
      }
    }
    // 获取月执行枚举
    const getMonthExecOptions = async () => {
      const { code, data } = await API.enumBao.getMonthBme();
      if (code === 200 && Array.isArray(data)) {
        state.monthExecOptions = data;
      } else {
        console.log('获取setMonthExecOptions失败');
      }
    }

    onMounted(() => {
      getCycleTypesOptions();
      getWeekExecOptions();
      getMonthExecOptions();
      if (props.editData) {
        props.editData.cycleType = String(props.editData.cycleType);
        // 如果是临时任务 就不回显保存任务的表单
        if (props.editData.cycleType != '0') {
          state.ruleForm = { ...props.editData };
        }
      }
    });

    return () => {
      return (
        <div class="task-save-drawer-wrap">
          <el-drawer
            destroy-on-close={true}
            close-on-click-modal={false}
            append-to-body={true}
            modelValue={props.drawerVisible}
            custom-class="system-drawer"
            title="保存任务"
            size="680px"
            onClosed={handleClose}
          >
            <div class="task-drawer">
              <el-form
                ref={ruleFormRef}
                model={state.ruleForm}
                rules={state.rules}
                label-width="100px"
                class="demo-ruleForm"
              >
                <el-form-item label="任务名称" prop="taskName">
                  <el-input
                    size="large"
                    v-model={state.ruleForm.taskName}
                    placeholder="任务名称"
                  ></el-input>
                </el-form-item>
                <el-form-item label="业务含义" prop="taskDesc">
                  <el-input
                    size="large"
                    v-model={state.ruleForm.taskDesc}
                    type="textarea"
                  ></el-input>
                </el-form-item>

                <el-row gutter={18}>
                  <el-col span={12}>
                    <el-form-item label="任务周期" prop="cycleType">
                      <el-select
                        size="large"
                        v-model={state.ruleForm.cycleType}
                        placeholder="选择周期类型"
                        onChange={handleCycleChange}
                      >
                        {state.cycleTypes.map(item => (
                          <el-option
                            key={item.value}
                            label={item.label}
                            value={item.value}
                          ></el-option>
                        ))}
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col span={6}>
                    {state.ruleForm.cycleType === '1' && (
                      <el-form-item
                        label-width="0"
                        prop="fixedDate"
                      >
                        <el-date-picker
                          v-model={state.ruleForm.fixedDate}
                          type="date"
                          size="large"
                          value-format="YYYY-MM-DD"
                          placeholder="选择日期"
                          disabledDate={disabledDate}
                        ></el-date-picker>
                      </el-form-item>
                    )}
                    {state.ruleForm.cycleType === '2' && (
                      <el-form-item
                        label-width="0"
                        prop="fixedTime"
                      >
                        <el-time-picker
                          size="large"
                          value-format="HH:mm:ss"
                          format="HH:mm:ss"
                          v-model={state.ruleForm.fixedTime}
                          placeholder="选择时间"
                        ></el-time-picker>
                      </el-form-item>
                    )}

                    {state.ruleForm.cycleType === '3' && (
                      <el-form-item
                        label-width="0"
                        prop="cycleValue"
                      >
                        <el-select
                          clearable
                          size="large"
                          v-model={state.ruleForm.cycleValue[0]}
                          placeholder="请选择"
                        >
                          {state.weekExecOptions.map(item => (
                            <el-option
                              key={item.value}
                              label={item.label}
                              value={item.value}
                            ></el-option>
                          ))}

                        </el-select>
                      </el-form-item>
                    )}

                    {state.ruleForm.cycleType === '4' && (
                      <el-form-item
                        label-width="0"
                        prop="cycleValue"
                      >
                        <el-select
                          clearable
                          size="large"
                          v-model={state.ruleForm.cycleValue[0]}
                          placeholder="请选择"
                        >
                          {state.monthExecOptions.map(item => (
                            <el-option
                              key={item.value}
                              label={item.label}
                              value={item.value}
                            ></el-option>
                          ))}
                        </el-select>
                      </el-form-item>
                    )}

                  </el-col>
                  <el-col span={6}>
                    {(state.ruleForm.cycleType === '1' ||
                      state.ruleForm.cycleType === '3' ||
                      state.ruleForm.cycleType === '4') && (
                        <el-form-item
                          label-width="0"
                          prop="fixedTime"
                        >
                          <el-time-picker
                            size="large"
                            value-format="HH:mm:ss"
                            format="HH:mm:ss"
                            v-model={state.ruleForm.fixedTime}
                            placeholder="选择时间"
                          ></el-time-picker>
                        </el-form-item>
                      )}

                  </el-col>
                </el-row>
                <el-row gutter={18}>
                  <el-col span={12}>
                    <el-form-item label="过期时间" prop="expireTime">
                      <el-date-picker
                        size="large"
                        v-model={state.ruleForm.expireTime}
                        type="datetime"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        placeholder="过期时间"
                        disabledDate={disabledDate}
                      ></el-date-picker>
                    </el-form-item >
                  </el-col>
                </el-row>
              </el-form >
              <div class="footer-btn">
                <ElButton
                  v-loading={props.saveLoading}
                  type="primary"
                  onClick={() => { submitForm('ruleForm') }}>生成</ElButton>
                <ElButton onClick={() => { resetForm('ruleForm') }}>取消</ElButton>
              </div>
            </div>
          </el-drawer >
        </div >
      );
    };
  }
});

export default TaskSaveDrawer;
